package com.css.prompt.service;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.css.prompt.model.PromptTemplate;
import com.css.prompt.repository.PromptTemplateRepository;

@Service
public class PromptTemplateService {

    private final PromptTemplateRepository repository;

    public PromptTemplateService(PromptTemplateRepository repository) {
        this.repository = repository;
    }

    public List<PromptTemplate> getAll() {
        return repository.findAll();
    }

    public Optional<PromptTemplate> getById(Long id) {
        return repository.findById(id);
    }

    public PromptTemplate save(PromptTemplate template) {
    	template.setLastModified(LocalDate.now());
    	template.setCreatedAt(LocalDate.now());
        return repository.save(template);
    }

    public PromptTemplate update(Long id, PromptTemplate newTemplate) {
        return repository.findById(id)
                .map(existing -> {
                    existing.setName(newTemplate.getName());
                    existing.setDescription(newTemplate.getDescription());
                    existing.setTemplateType(newTemplate.getTemplateType());
                    existing.setType(newTemplate.getType());
                    existing.setStatus(newTemplate.getStatus());
                    existing.setLastModified(LocalDate.now());
                    existing.setContent(newTemplate.getContent());
                    return repository.save(existing);
                })
                .orElseThrow(() -> new RuntimeException("模板不存在"));
    }

    public void delete(Long id) {
        repository.deleteById(id);
    }
    
    public Page<PromptTemplate> getPage(Pageable pageable) {
        return repository.findAll(pageable);
    }

    public Page<PromptTemplate> searchByName(String name, Pageable pageable) {
        return repository.findByNameContainingIgnoreCase(name, pageable);
    }
}

